package DataStructureAndAlgorithm.CSP.Day14;
import java.util.Scanner;
//博弈论
//一个取自己最多，一个取对方最少
//深搜枚举每一种情况
//链接：https://www.acwing.com/problem/content/3263/
public class AcWing_3260 {
    static int MAX = 100000010;
    static int N = 3;
    static int t;
    static int g[][] = new int[N][N];
    public static void main(String[] args){
        Scanner in = new Scanner (System.in);
        t = in.nextInt();
        for (int i = 0; i < t; i++){
            for (int j = 0; j < 3; j++){
                for (int k = 0; k < 3; k++){
                    g[j][k] = in.nextInt();
                }
            }
            System.out.println(dfs(0));
        }
    }
    //深搜每一种情况，求最优
    static int dfs(int u){
        int t = evalute();
        if (t != MAX){
            return t;
        }

        if (u == 0){
            int res = -MAX;
            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 3; j++){
                    if (g[i][j] == 0){
                        g[i][j] = 1;
                        res = Math.max(res,dfs(1));
                        //还原现场
                        g[i][j] = 0;
                    }
                }
            }
            return res;
        }else {
            int res = MAX;
            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 3; j++){
                    if (g[i][j] == 0){
                        g[i][j] = 2;
                        res = Math.min(res,dfs(0));
                        //还原现场
                        g[i][j] = 0;
                    }
                }
            }
            return res;
        }
    }
    //评估棋局，返回当前棋局的分数
    static int evalute(){
        int s = 0;
        for (int i = 0; i < 3; i++){
            for (int j = 0; j < 3; j++){
                if (g[i][j] == 0){
                    s++;
                }
            }
        }
        if (check(1))return s + 1;
        if (check(2))return -(s + 1);
        if (s == 0)return 0;
        return MAX;
    }
    static boolean check(int x){
        for (int i = 0; i < 3; i++){
            int s = 0;
            //枚举每一行
            for (int j = 0; j < 3; j++){
                if (g[i][j] == x){
                    s++;
                }
            }
            if (s == 3)return true;
            s = 0;
            //枚举每一列
            for (int j = 0; j < 3; j++){
                if (g[j][i] == x){
                    s++;
                }
            }
            if (s == 3)return true;
        }
        //枚举对角线
        if (g[0][0] == x && g[1][1] == x && g[2][2] == x)return true;
        if (g[2][0] == x && g[1][1] == x && g[0][2] == x)return true;
        //如果所有情况都不能练成三个连续的，则返回false
        return false;
    }
}
